package com.wulian.user.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.wulian.common.constants.CommonConstants;
import com.wulian.common.constants.UserConstant;
import com.wulian.common.dto.UserInfo;
import com.wulian.common.entity.SysUserDataPermission;
import com.wulian.common.util.JSONUtil;
import com.wulian.user.mapper.SysUserDataPermissionMapper;
import com.wulian.user.service.SysUserDataPermissionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
@Transactional
public class SysUserDataPermissionServiceImpl extends ServiceImpl<SysUserDataPermissionMapper, SysUserDataPermission> implements SysUserDataPermissionService {
	@Autowired
	private SysUserDataPermissionMapper sysUserDataPermissionMapper;
	@Autowired
	StringRedisTemplate redisTemplate;

    /**
     * 
    * @Title: synUserInfoToRedis
    * @Description:(更改的数据权限同步至redis)
    * @param @param userId    参数
    * @return void    返回类型
    * @author mzh
    * @date 2020年4月7日
    * @version V1.0
    * @throws
     */
	private void synUserInfoToRedis(Integer userId) {
		// 获取当前用户的token
		String token = redisTemplate.opsForValue().get(UserConstant.USER_ID_TOKEN_PREFIEX + userId);
		// 通过token获取用户数据
		String userInfoJson = redisTemplate.opsForValue().get(CommonConstants.USER_TOKEN_PREFIEX + token);

		if (StringUtils.isNotBlank(userInfoJson)) {
			UserInfo user = JSONUtil.fromJSON(userInfoJson, UserInfo.class);
			// 查询当前用户所拥有的数据权限
			Map<String, Object> columMap = new HashMap<String, Object>();
			columMap.put("USER_ID", userId);
			columMap.put("DEL_FLAG", CommonConstants.DEL_FLAG_NO);
			List<SysUserDataPermission> sysUserDataPermissionList = sysUserDataPermissionMapper.selectByMap(columMap);
			user.setSysUserDataPermissionList(sysUserDataPermissionList);
			redisTemplate.opsForValue().set(UserConstant.USER_TOKEN_PREFIEX + token, JSONUtil.toJSON(user));
		} else {
			log.error("获取当前用户信息异常");
		}
	}
	
}
